/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package pua.uniandes.monitoreo;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Date;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.naming.InitialContext;
import pua.uniandes.interfaz.InterfazCentroMonitoreo;
import pua.uniandes.servicios.ReporteMisionesBeanRemote;
import sun.applet.Main;

/**
 *
 * @author jd.velasquez3209
 */
public class Monitoreo {

    private ServerSocket server;
    private Socket cliente;
    private BufferedReader in;
    private static final int CANTIDAD_PAQUETE = 20;
    private InterfazCentroMonitoreo icm;
    private ArrayList<double[]> tramasGuardadas;
    private ReporteMisionesBeanRemote rmbr;
    private Integer numTramas;

    public Monitoreo(InterfazCentroMonitoreo inter)
    {
        icm=inter;
        tramasGuardadas=new ArrayList<double[]>();
        crearConexion();
//        crearMision();
//        iniciarMision();
//        establecerConexion();
        recepcionTransmisionVideo();
    }

    public void crearConexion(){
         try {
         System.out.println("Va a tratar de crear la trama");
            Properties props = new Properties();
            props.load(new FileInputStream("jndi.properties"));
            InitialContext ctx = new InitialContext(props);
            rmbr = (ReporteMisionesBeanRemote) ctx.lookup("java:global/Experimento1MonitoreoControl/Experimento1MonitoreoControl-ejb/ReporteMisionesBean!pua.uniandes.servicios.ReporteMisionesBeanRemote");
            System.out.println("La conexión fue exitosa");
        }
         catch (Exception ex){
            Logger.getLogger(Monitoreo.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void establecerConexion()
	{
		try {
			server= new ServerSocket(7854);
			cliente=server.accept();
			in = new BufferedReader(new InputStreamReader(cliente.getInputStream()));
			String cadena="";
//                        while(cadena!=null||!cadena.isEmpty())
			for(int j=0;j<numTramas;j++)
                        {
				cadena=in.readLine();
				System.out.println(cadena);
                                System.out.println("LALALA CADENA:"+cadena);
                                String[] datos= cadena.split("@");
                                Date fecha=new Date((Long.parseLong(datos[6])));
                                cadena=cadena.replace(datos[6], fecha+"("+datos[6]+")");
				icm.actualizar(cadena);
                                double[] result=new double[datos.length];
                                for (int i = 0; i < datos.length; i++) {
                                    result[i]=Double.parseDouble(datos[i]);
                                    System.out.println("result"+i+":"+result[i]);
                                 }

                                tramasGuardadas.add(result);
			}
                        icm.pintarGrafica(tramasGuardadas);
                        System.out.println("Salió del ciclo");
                        System.out.println("Tamaño tramasGuardadas:"+tramasGuardadas.size());
                         for (int i = 0; i < tramasGuardadas.size(); i++) {
                             HiloGuardarTramas hilo=new HiloGuardarTramas(tramasGuardadas.get(i), rmbr);
                             hilo.start();

                    System.out.println("Guardó la trama efectivamente");
//                        }

		}} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

               
            
                
	}
    
    public void recepcionTransmisionVideo() {

        try {
            server = new ServerSocket(4646);
                    try {
                        for (int i = 0; i < CANTIDAD_PAQUETE; i++) {

                            System.out.println("Waiting for connection...");
                            cliente = server.accept();
                            System.out.println("Connection succesful:" + cliente);

                            File f = new File("video" + i + ".txt");

                            InputStream is = cliente.getInputStream();
                            receiveFile(f, is);
                            Socket envio = new Socket("127.0.0.1", 2525);
                            sendFile(f, envio);
                            envio.close();

                            cliente.close();
                        }
                        
                    } catch (ClassNotFoundException ex) {
                Logger.getLogger(Monitoreo.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IOException ex) {
                        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                    }

                }
        catch (IOException ex) {
            Logger.getLogger(Monitoreo.class.getName()).log(Level.SEVERE, null, ex);
        }





    }

    public void receiveFile(File file, InputStream is) throws IOException {
        byte[] b = new byte[1024];
        int len = 0;
        int bytcount = 1024;
        FileOutputStream inFile = new FileOutputStream(file);

        BufferedInputStream in2 = new BufferedInputStream(is, 1024);
        while ((len = in2.read(b, 0, 1024)) != -1) {
            bytcount = bytcount + 1024;
            inFile.write(b, 0, len);
        }

        System.out.println("Bytes Writen : " + bytcount);

        // Sending the response back to the client.
        ObjectOutputStream oos = new ObjectOutputStream(cliente.getOutputStream());
        oos.flush();
        oos.writeObject("ok");
        System.out.println("Message sent to the client is " + "ok");


        inFile.close();
    }

    private void sendFile(File file, Socket socket) throws IOException, ClassNotFoundException {
        byte[] buf = new byte[1024];


        OutputStream os = socket.getOutputStream();
        BufferedOutputStream out = new BufferedOutputStream(os, 1024);
        FileInputStream in = new FileInputStream(file);
        int i = 0;
        int bytecount = 1024;
        while ((i = in.read(buf, 0, 1024)) != -1) {
            bytecount = bytecount + 1024;
            out.write(buf, 0, i);
            out.flush();
        }

        socket.shutdownOutput(); /* important */
        System.out.println("Bytes Sent :" + bytecount);

        ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
        ois.skip(Long.MAX_VALUE);
        String confirmation = (String) ois.readObject();
        System.out.println("from server : " + confirmation);
        in.close();
    }

    public boolean crearMision(String nombre, String cohete)
    {
        try {
            rmbr.crearMision(nombre, cohete, new Date(System.currentTimeMillis()));
            return true;
        } catch (Exception ex) {
            ex.printStackTrace();
            return false;
        }
    }

    public void setNumTramas(int i){
        numTramas=i;
    }


    public boolean iniciarMision(String name)
    {
        try {
//            System.out.println("Va a tratar de iniciar la misión");
//            Properties props = new Properties();
//            props.load(new FileInputStream("jndi.properties"));
//            InitialContext ctx = new InitialContext(props);
//            ReporteMisionesBeanRemote rmbr = (ReporteMisionesBeanRemote) ctx.lookup("java:global/Experimento1MonitoreoControl/Experimento1MonitoreoControl-ejb/ReporteMisionesBean!pua.uniandes.servicios.ReporteMisionesBeanRemote");

           return rmbr.iniciarMision(name);
        } catch (Exception ex) {
            Logger.getLogger(Monitoreo.class.getName()).log(Level.SEVERE, null, ex);
        }
        return false;
    }


    public void guardarTrama(double aceX,double aceY,double aceZ,double alt,double pote,double temp,Date tiemp){
        try {
            System.out.println("Va a tratar de crear la trama");
            Properties props = new Properties();
            props.load(new FileInputStream("jndi.properties"));
            InitialContext ctx = new InitialContext(props);
            ReporteMisionesBeanRemote rmbr = (ReporteMisionesBeanRemote) ctx.lookup("java:global/Experimento1MonitoreoControl/Experimento1MonitoreoControl-ejb/ReporteMisionesBean!pua.uniandes.servicios.ReporteMisionesBeanRemote");

            rmbr.guardarTrama(aceX, aceY, aceZ, alt, pote, temp, tiemp);
            System.out.println("si pudo guardarla");
        } catch (Exception ex) {
            Logger.getLogger(Monitoreo.class.getName()).log(Level.SEVERE, null, ex);
        } 
    }




//    public static void main (String[] args){
//        new Monitoreo();
//    }


}

class HiloGuardarTramas extends Thread{
    private double[] tramas;
    private ReporteMisionesBeanRemote rmbr;
    public HiloGuardarTramas(double[] trama, ReporteMisionesBeanRemote rm) {
        tramas=trama;
        rmbr=rm;
    }

    @Override
    public void run(){
            Date fecha=new Date((long) tramas[6]);
            rmbr.guardarTrama(tramas[0], tramas[1], tramas[2], tramas[3], tramas[4], tramas[5], fecha);
            System.out.println("si pudo guardarla");

    }

}